package it.lefo.dateReminder;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import it.lefo.dateReminder.bo.ContactsRepository;
import it.lefo.dateReminder.helper.DbHelper;
import it.lefo.dateReminder.helper.Utilities;
import it.lefo.dateReminder.model.Contact;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddEventView extends Activity implements OnClickListener, TextWatcher {
	
	private EditText txtName;
	private EditText txtSurname;
	private EditText txtNickname;
	private EditText txtMessage;
	private Spinner ddlTypeEvent;
	private EditText txtPhone;   
	private Button btnSave;
	private Date dateSelected;
	private DatePicker datepicker;
	private boolean isValidForm = false;	
	private ContactsRepository _cntRepo;
	private SQLiteDatabase _db;
	private List<Contact> _contacts = new ArrayList<Contact>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.addevent);
	    
	    //DB connection
        DbHelper dbh = new DbHelper(this);          
		try {
			//db connection
			_db = dbh.getOrCreateDataBase();
			_cntRepo = new ContactsRepository(_db);
		}catch(Exception e){
			Log.e("AddEventView", "Errore durante la connessione al db. Exc Message: " + e.getMessage() + ". Exc StakTrace: " +  e.getStackTrace());
		}

	    //FindElements
	    txtName = (EditText)findViewById(R.id.txtName);
	    txtSurname = (EditText)findViewById(R.id.txtSurname);
	    txtNickname = (EditText)findViewById(R.id.txtNickname);
	    txtMessage = (EditText)findViewById(R.id.txtMessage);
	    ddlTypeEvent = (Spinner)findViewById(R.id.ddlTypeEvent);
	    txtPhone = (EditText)findViewById(R.id.txtPhone);  
	    btnSave = (Button)findViewById(R.id.btnAddEvent);
	    datepicker = (DatePicker)findViewById(R.id.dpkBirthday);
	    
	    //Get all the get parameters
	    Bundle bundle = this.getIntent().getExtras();	    
	    Integer id = null;
	    
        try{
        	dateSelected = Utilities.StringToDate(bundle.getString("dateSelected"));
        	id = Integer.parseInt(bundle.getString("id"));
        	int year = dateSelected.getYear()+1900;
    	    int month = dateSelected.getMonth();
    	    int day = dateSelected.getDay();
    	    datepicker.init(year,month, day, null);
        }catch(Exception e){
        	
        }
	    
	    btnSave.setOnClickListener(this);
	    txtName.addTextChangedListener(this);
	    txtSurname.addTextChangedListener(this);
	    txtNickname.addTextChangedListener(this);
	    txtPhone.addTextChangedListener(this);
	    
	    
	    
		Spinner s = (Spinner) findViewById(R.id.ddlTypeEvent);
	    ArrayAdapter adapter = ArrayAdapter.createFromResource(
	            this, R.array.typeevent, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    s.setAdapter(adapter);
	}
	
	@Override
	public void onClick(View v){
		
		if (v == btnSave){			
	        try {
	        	
	        	DbHelper dbh = new DbHelper(this);
				SQLiteDatabase db= dbh.getOrCreateDataBase();
				
				Date dtSelected = new Date(datepicker.getYear()-1900, datepicker.getMonth(), datepicker.getDayOfMonth());
				ContentValues cv = new ContentValues();
				cv.put("typeevent", (String) ddlTypeEvent.getItemAtPosition((int) ddlTypeEvent.getSelectedItemId()));
				cv.put("phone", txtPhone.getText().toString());
				cv.put("name", txtName.getText().toString());
				cv.put("surname", txtSurname.getText().toString());
				cv.put("nickname", txtNickname.getText().toString());
				cv.put("txtmessage", txtMessage.getText().toString());
				cv.put("birthdate", Utilities.DateToString(dtSelected, "dd/MM/yyyy"));
				
				ValidateForm();
				if (isValidForm){
					//Insertion
					db.insert("contacts", null, cv);
					
					//Select from db
					_contacts = _cntRepo.getAllContactsInDate(dtSelected);
					
					//Bundle
					Intent i = new Intent(AddEventView.this,EventsInDateView.class);
					Bundle bundle = new Bundle();
					bundle.putString("dateSelected", Utilities.DateToString(dtSelected, "dd/MM/yyyy"));
					bundle.putSerializable("contacts", (Serializable) _contacts);
					i.putExtras(bundle);		
					startActivity(i);
				}
				else{
					Toast toast = Toast.makeText(this, "Dati non validi. Correggere e riprovare", Toast.LENGTH_LONG);
					toast.show();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
	}
	
	private void ValidateForm(){
		String txtName_value = txtName.getText().toString();
		String txtSurname_value = txtSurname.getText().toString();
		String txtNickname_value = txtNickname.getText().toString();
		
		if ((txtName_value.length() == 0) || (txtSurname_value.length() == 0) || (txtNickname_value.length() == 0) || (!Utilities.isAValidPhoneNumber(txtPhone.getText().toString())))
			isValidForm = false;
		else
			isValidForm = true;
	}

	@Override
	public void afterTextChanged(Editable s) {				
		
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}
}
